import {EventEmitter} from './utils/events'
import {defaultOptions, formatOptions, mergeOptions} from './utils/option'
import is from './utils/is'
import initDom from './internal/initDom'
import initVideo from './internal/initVideo'
import initMSE from './internal/initMSE'
import initTimer from './internal/initTimer'

export default class Player extends EventEmitter {
  constructor (containerId) {
    super()

    // config
    this._config = {}
    this._config.containerId = containerId
    this._container = document.getElementById(this._config.containerId)

    // base class
    this._baseClass = 'viil'

    // running status
    this._status = {
      state: 'idle',
      focus: false,
      duration: 0,
      position: 0
    }

    this.dom = {}
    this.timer = {}
    this.controller = {}
  }

  setup (options) {
    const formatedOptions = formatOptions(options)
    const mergedOptions = mergeOptions(Player.defaultOptions, formatedOptions)
    this._config = {...this._config, ...mergedOptions}

    console.log(this._config)

    if (!is('array', this._config.playlist)) {
      throw new Error(
        'setup(options): ' +
          'you should give me a video url to play, through' +
          '`options.file` or `options.playlist` array'
      )
    }

    // set active
    this._config.playlist[0].active = true
    this._config.playlist[0].sources[0].active = true

    initDom.call(this)
    initVideo.call(this)
    initMSE.call(this)
    initTimer.call(this)
  }

  getPlugins () {
    return Player.plugins
  }
}

Player.plugins = {}
Player.defaultOptions = defaultOptions
Player.setDefaultOptions = function (options) {
  // TODO: not direct change defaultOptions
  Player.defaultOptions = mergeOptions(defaultOptions, options)
}
Player.registerPlugin = function (name, plugin) {
  if (!is('function', plugin)) {
    throw new Error(
      `viil.registerPlugin(name, plugin), plugin should be a function, but got ${typeof plugin}.`
    )
  }
  if (Player.plugins[name]) {
    console.warn(
      `plugin '${name}' has been registered, will not be registered twice.` +
        `If you want to register the plugin, please change a name.`
    )
    return
  }
  Player.plugins[name] = {
    plugin: plugin
  }
}
Player.getPlugins = function () {
  return Player.plugins
}
